package net.wicp.tams.common.web;

import net.wicp.tams.common.apiext.StringUtil;

public abstract class JPQLAssit {
	/***
	 * 通过JPQL 得到要count()的字段
	 * 
	 * @param queryStr
	 *            查询的JPQL
	 * @return 转为对应count()的JPQL
	 */
	public static String getCountCol(String queryStr) {
		int firstIndex = queryStr.toLowerCase().indexOf(" from");
		int firstDoc = queryStr.indexOf(".");
		String countStr = "";
		if (firstDoc < firstIndex) {
			int pre = firstDoc;
			boolean hasChart = true;
			do {
				pre--;
				if ((queryStr.charAt(pre) >= 'a' && queryStr.charAt(pre) <= 'z')
						|| (queryStr.charAt(pre) >= 'A' && queryStr.charAt(pre) <= 'Z') && hasChart) {
					hasChart = false;
				}
			} while (pre >= 0 && ((queryStr.charAt(pre) >= 'a' && queryStr.charAt(pre) <= 'z')
					|| (queryStr.charAt(pre) >= 'A' && queryStr.charAt(pre) <= 'Z')) || hasChart);

			int pos = firstDoc;
			hasChart = true;
			do {
				pos++;
				if ((queryStr.charAt(pos) >= 'a' && queryStr.charAt(pos) <= 'z')
						|| (queryStr.charAt(pos) >= 'A' && queryStr.charAt(pos) <= 'Z') && hasChart) {
					hasChart = false;
				}
			} while (pos < firstIndex && ((queryStr.charAt(pos) >= 'a' && queryStr.charAt(pos) <= 'z')
					|| (queryStr.charAt(pos) >= 'A' && queryStr.charAt(pos) <= 'Z')) || hasChart);
			countStr = queryStr.substring(pre + 1, pos);
		} else {
			countStr = queryStr.substring(0, firstIndex);
			countStr = StringUtil.trimSpace(countStr.replace("select", ""));
		}

		countStr = countStr.replace(" ", "");
		return StringUtil.hasNull(countStr);
	}
}
